#include <stdint.h>
#include "Drv_KEY.h"
#include "App_DAC.h"
#include "App_OLED.h"
#include "debug.h"

// 1mA对应0.1V
#define CURRENT_STEP	(0.1f)
#define MAX_CURRENT		(2.0f)
#define MIN_CURRENT		(0.4f)
/**
***********************************************************
* @brief 按键事件处理
* @param
* @return 
***********************************************************
*/
void Key_EventHandle(void)
{
	uint8_t key_event = GetKeyVal();
	static float val = 0.4f;
	static uint8_t isPress = 0; // 默认不支持连按
	char strTmp[30] = { 0 };
	
	switch(key_event)
	{
		case KEY1_SHORT_PRESS:
		{
			if(!isPress)
			{
				p_dbg("KEY1_SHORT_PRESS");
				val += CURRENT_STEP;
				if(val > MAX_CURRENT)
				{
					p_info("The DAC Value is Overflow!");
					val = MAX_CURRENT;
					OLED_ShowStr(0, 2*18, (uint8_t *)"Over Range", TextSize_8x16);
				}
				else
				{
					OLED_ShowStr(0, 2*18, (uint8_t *)"          ", TextSize_8x16);
				}
				
				DAC_SetOutputVoltage(val);
				p_info("DAC Output Value:%d,%f", DAC_GetValue(), DAC_GetVoltage());
				isPress = 1;
			}
		}			
		break;
		
		case KEY1_LONG_PRESS:
		{
			p_dbg("KEY1_LONG_PRESS");
		}			
		break;
		
		case KEY2_SHORT_PRESS:
		{
			if(!isPress)
			{
				p_dbg("KEY2_SHORT_PRESS");
				val -= CURRENT_STEP;
				if(val < MIN_CURRENT)
				{
					p_info("The DAC Value is min to Limit!");
					val = MIN_CURRENT;
					OLED_ShowStr(0, 2*18, (uint8_t *)"Over Range", TextSize_8x16);
				}				
				else
				{
					OLED_ShowStr(0, 2*18, (uint8_t *)"          ", TextSize_8x16);
				}
				
				DAC_SetOutputVoltage(val);
				p_info("DAC Output Value:%d,%f", DAC_GetValue(), DAC_GetVoltage());
				isPress = 1;
			}
		}			
		break;
		
		case KEY2_LONG_PRESS:
		{
			p_dbg("KEY2_LONG_PRESS");
		}
		break;
		
		default:
		{
			isPress = 0;
		}
		break;
	}
	
	if(isPress) // 如果有按键被按下，更新输出值
	{
		sprintf(strTmp, "%.2lf mA", DAC_GetVoltage() * 10);
		OLED_ShowStr(7*8 + 1, 18, (uint8_t *)strTmp, TextSize_8x16);
	}
}
